<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/11/27 下午5:35
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/11/27 下午5:35
 * @FilePath: G:/chain-link-api-front-admin/src/views/categoryManagement\index.vue
 * @Description: 类别管理
-->
<template>
  <!-- 查询 -->
  <div class="queryBar">
    <div class="query_btns">
      <!-- 新增单个套餐 -->
      <el-button type="primary" plain :icon="Plus" size="small" @click="handleCLickDialogTrue('add')">
        {{ $t('button.Add') }}
      </el-button>
    </div>
  </div>

  <el-table :data="tableData" stripe border style="width: 100%; " size="large" v-loading="loading" max-height="700px">
    <el-table-column prop="id" :label="$t('category.categoryId')" width="auto" align="center" />
    <el-table-column prop="name" :label="$t('category.categoryName')" width="auto" align="center" />
    <el-table-column prop="desc" :label="$t('category.categoryDesc')" width="auto" align="center" />


    <el-table-column fixed="right" :label="$t('global.Operation')" width="auto" align="center">
      <template #default="scope">
        <!-- 修改套餐按钮 -->
        <el-button type="success" plain :icon="Edit" size="small" @click="handleCLickDialogTrue('edit', scope.row)">
          {{ $t('button.Edit') }}
        </el-button>
        <!-- 删除套餐按钮 -->
<!--        <el-button type="danger" plain :icon="Delete" size="small" @click="deleteProductBtn(scope.row)">-->
<!--          {{ $t('button.Del') }}-->
<!--        </el-button>-->
      </template>
    </el-table-column>

  </el-table>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>


  <!-- 新增类别 -- 弹出对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="ruleForm.formTitle" width="500" @close="closeDialog">
    <el-form :model="ruleForm">
      <el-form-item :label="t('category.categoryName')" :label-width="formLabelWidth">
        <el-input style="width: 80%;" v-model.trim="ruleForm.categoryName" :placeholder="$t('global.PleaseInput') + $t('category.categoryName')" />
      </el-form-item>
      <el-form-item :label="t('category.category')" :label-width="formLabelWidth">
        <el-select  style="width: 80%;" v-model.trim="ruleForm.categoryDesc" :loading="loading" :placeholder="$t('global.PleaseSelect') + $t('category.category')">
          <el-option v-for="(item, index) in options" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('global.emailCode')" :label-width="formLabelWidth">
        <el-input style="width: 30%;" v-model="ruleForm.code"></el-input>
        <el-button style="width: 50%;" @click="getEmailCode" :disabled="isThrottled">
          <span v-show="!isThrottled">
            {{ $t('global.GetCode') }}
          </span>
          <span v-show="isThrottled">
            {{ `${remainingTime}${$t('global.reSendCode')}` }}
          </span>
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleCLickDialogFalse"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup>
import { ref, onMounted, unref, reactive } from 'vue'
import { Delete, Edit, Plus, Refresh, Search, Upload } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import { formatTimestamp } from "@/utils/timeStamp";
import { ElPagination, ElMessage, ElTable, ElMessageBox } from "element-plus";
import { createCategory, categoryList, updateCategory, getEmailCodeApi } from '@/require/api.js'
const { t } = useI18n();
import { useUserStore } from "@/stores";

const userStore = useUserStore();

// 关闭弹窗
function closeDialog(){
  resetForm();
  dialogFormVisible.value = false;
}

// 清除 ruleForm
function resetForm(){
  ruleForm.categoryName = '';
  ruleForm.categoryDesc = '';
  ruleForm.formTitle = '';
  ruleForm.id = '';
  ruleForm.code = '';
}

// 查询参数
const queryParams = reactive([
  {
    id: '',
    orderStatus: ''
  }
])

const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const tableData = ref([])

// 新增或修改套餐 弹出的对话框中使用
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const ruleForm = reactive({
  id: '',
  formTitle: '',
  categoryName: '',
  categoryDesc: '',
  code: '',
})

// 下拉菜单
const value = ref('')

const options = [
  {
    value: 'dapp',
    label: 'dapp',
  },
  {
    value: 'blockWatch',
    label: 'blockWatch',
  },
]


onMounted(() => {
  getList();
});

const loading = ref(false);

const readyPatchObj = ref({})

// 点击按钮方法
const handleCLickDialogTrue = (val1, val2) => {
  console.log(val1, val2)
  dialogFormVisible.value = true;
  handleType.value = val1

  switch (val1) {
    case 'add':
      // 点击添加套餐按钮
      ruleForm.formTitle = t('category.AddCategory')
      ruleForm.categoryName = ''
      break;
    case 'edit':
      // 点击修改套餐按钮
      ruleForm.formTitle = t('category.EditCategory')
      ruleForm.id = val2.id
      ruleForm.categoryName = val2.name
      ruleForm.categoryDesc = val2.desc
      break;
    default:
      break;
  }
}

// 是否处于节流状态
const isThrottled = ref(false);
// 发送验证码剩余时间
let remainingTime = ref(60);

// 节流函数
function throttle(fn) {
  // 如果处于节流状态，直接返回
  if (isThrottled.value) return;
  isThrottled.value = true;
  fn();
}

// 倒计时函数
function startCountdown(seconds) {
  remainingTime.value = seconds;
  const interval = setInterval(() => {
    remainingTime.value -= 1;
    if (remainingTime.value <= 0) {
      clearInterval(interval);
      isThrottled.value = false;
    }
  }, 1000);
}

// 发送验证码
function getEmailCode(){
  throttle(async () => {
    try {
      const formData = new FormData();
      formData.append('to', userStore.getUserInfo.email);
      await getEmailCodeApi(formData);
      ElMessage.success(t('message.GetCodeSuccess'));
      startCountdown(60);
    } catch(error) {
      console.log('getEmailCodeApi - error', error);
    }
  });
};

// 点击按钮类型
const handleType = ref('')
// 关闭对话框
const handleCLickDialogFalse = (val) => {
  switch (handleType.value) {
    case 'add':
      if (ruleForm.categoryName == '' || ruleForm.categoryDesc == '') {
        ElMessage.error(t('message.InputAll'))
        return
      }
        createProductBtn()
      break;
    case 'edit':
      if (ruleForm.categoryName == '' || ruleForm.categoryDesc == '' ) {
        ElMessage.error(t('message.InputAll'))
      } else {
        // 调用修改套餐方法
        patchProductBtn()
      }
      break;
    default:
      break;
  }
}

// 检查 ruleForm.fee 的输入内容
function ChangeNumValue(tmpVal) {
  // console.log('ChangeNumValue');
  if (tmpVal) {
    var tmpVal = tmpVal.replace(/[^\d\.]/g, '');
    var reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/; //正则验证保留 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + "";
      tmpVal = tmpVal.substring(0, tmpVal.indexOf(".") + 3);
      var n = (tmpVal.split('.')).length - 1;
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf("."));
      }
    }
    return tmpVal + '';
  } else {
    return "";
  }
}

// 处理时间输入
const updateNumber = () => {
  // 尝试将输入字符串转换为数字
  const inputValue = parseFloat(ruleForm.months);
  // 检查转换是否成功（即输入是否为有效的数字）
  if (!isNaN(inputValue)) {
    ruleForm.months = inputValue;
  } else {
    // 如果转换失败，可以将 numberValue 重置为 null 或其他默认值
    ruleForm.months = 1;
  }
}


// 获取套餐列表
async function getList() {
  try {
    loading.value = true
    const { code, data, msg } = await categoryList({
      pageIndex: unref(pageIndex),
      pageSize: unref(pageSize),
    })
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 添加类别
async function createProductBtn() {
  const params = {
    name: ruleForm.categoryName,
    desc: ruleForm.categoryDesc,
    code: ruleForm.code
  }
  let res = await createCategory(params)
  if (res.code == 200) {
    ElMessage.success(t('message.AddSuccess'))
  } else {
    ElMessage.error(res.msg);
  }
  closeDialog();
  // 修改后，再次获取类别列表信息刷新
  await getList();
}

// 修改类别
async function patchProductBtn() {
  const params = {
    id: ruleForm.id,
    name: ruleForm.categoryName,
    desc: ruleForm.categoryDesc,
    code: ruleForm.code
  }
  let res = await updateCategory(params);
  if (res.code === 200) {
    ElMessage.success(t('message.EditSuccess'));
  } else {
    ElMessage.error(res.msg);
  }
  closeDialog();
  // 修改后，再次获取套餐列表信息刷新
  await getList();
}

// 删除套餐
// function deleteProductBtn(rowData) {
//   ElMessageBox.confirm(
//       t('global.DeleteInfo'),
//       t('global.DeleteInfoImportance'),
//       {
//         confirmButtonText: t('global.OK'),
//         cancelButtonText: t('global.Cancel'),
//         type: 'warning',
//       }
//   )
//       .then(async () => {
//         let obj = { "id": rowData.id }
//         let res = await deleteProduct(obj)
//
//         // 修改后，再次获取套餐列表信息刷新
//         getList();
//
//         ElMessage({
//           type: 'success',
//           message: t('global.DeleteCompleted'),
//         })
//       })
//       .catch(() => {
//         ElMessage({
//           type: 'info',
//           message: t('global.DeleteCanceled'),
//         })
//       })
// }

// 套餐时间单位 国际化
function formatProductType(productType) {
  switch (productType) {
    case '1':
      return t('package.Years');
    case '2':
      return t('package.Months');
    case '3':
      return t('package.Days');
    case '4':
      return t('package.Hours');
  }
}

// 搜索方法
const onSubmit = (id, orderStatus) => {
  // 查询时把 pageIndex 重置为1
  pageIndex.value = 1
  getList(id, orderStatus);
}
// 清除  queryParams
const onClear = () => {
  queryParams.id = ''
  queryParams.orderStatus = ''
}

// 重置方法
const onReset = () => {
  onClear();
  getList();
}

// 分页
function handleSizeChange(val) {
  pageSize.value = val
  getList()
}

// 分页
function handleCurrentChange(val) {
  pageIndex.value = val
  getList(queryParams.id, queryParams.orderStatus)
}
</script>

<style scoped lang="less">
.queryBar {
  background-color: #fff;
  margin: .1rem 0;
  padding: .1rem 0;
  box-sizing: border-box;

  .demo-form-inline {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
  }

  .query_btns {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    margin: .15rem 0 0 0;
  }
}
</style>
